package weaver.interfaces.zlldjcws.cgdd.service.impl;

import com.weaver.general.BaseBean;
import com.weaver.general.Util;
import weaver.conn.RecordSet;
import weaver.interfaces.zlldjcws.util.Message;
import weaver.interfaces.zlldjcws.util.WorkflowCreateHandler;
import weaver.interfaces.zlldjcws.cgdd.bean.CgddBean;
import weaver.interfaces.zlldjcws.cgdd.bean.CgddDetail1Bean;
import weaver.interfaces.zlldjcws.cgdd.service.LdCgddService;

import javax.ejb.Stateless;
import javax.jws.WebService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ZhangLei
 * @date 2021/8/2
 */


@Stateless(mappedName = "LdCgddServiceImpl")
@WebService(serviceName = "LdCgddServiceImpl")
public class LdCgddServiceImpl extends BaseBean implements LdCgddService {
    private static String IsNextFlow = "0";
    private String WorkFlowId = getPropValue("CGDD_WORKFLOW", "WORKFLOWID");

    @Override
    public Message createModeData(CgddBean cgddBean) {
        writeLog("主表信息：");
        writeLog("ebeln:" + cgddBean.getEbeln());
        writeLog("bedat:" + cgddBean.getBedat());
        writeLog("bsart:" + cgddBean.getBsart());
        writeLog("lifnr:" + cgddBean.getLifnr());
        writeLog("ekorg:" + cgddBean.getEkorg());
        writeLog("ekgrp:" + cgddBean.getEkgrp());
        writeLog("bukrs:" + cgddBean.getBukrs());
        writeLog("frgke:" + cgddBean.getFrgke());
        writeLog("zflag:" + cgddBean.getZflag());
        writeLog("zspbs:" + cgddBean.getZspbs());
        writeLog("creator:" + cgddBean.getCreator());
        List<CgddDetail1Bean> cgddDetail1Beans = cgddBean.getCgddDetail1Beans();
        writeLog("明细表信息：(明细表数据共有" + cgddDetail1Beans.size() + "行数据）");
        if (cgddDetail1Beans.size() > 0) {
            for (CgddDetail1Bean cgddDetail1Bean : cgddDetail1Beans) {
                if (cgddDetail1Bean != null) {
                    writeLog(cgddDetail1Bean);
                }
            }
        }
        return createWorkFlowByPDM(cgddBean, cgddDetail1Beans);
    }

    private Message createWorkFlowByPDM(CgddBean cgddBean, List<CgddDetail1Bean> cgddDetail1Beans) {
        writeLog("进入createWorkFlowByPDM方法");
        Message message = new Message();
        RecordSet rs = new RecordSet();
        WorkflowCreateHandler workflowCreateHandler = new WorkflowCreateHandler();
        Map<String, String> requestMap = new HashMap<>();
        String creatorId = "";//创建人id
        if (cgddBean.getCreator() == null) {
            message.setFlag("E");
            message.setMessage("缺少创建人");
            message.setId("-300");
        } else {
            requestMap.put("EBELN".toLowerCase(), cgddBean.getEbeln());
            requestMap.put("BEDAT".toLowerCase(), cgddBean.getBedat());
            requestMap.put("BSART".toLowerCase(), cgddBean.getBsart());
            requestMap.put("LIFNR".toLowerCase(), cgddBean.getLifnr());
            requestMap.put("EKORG".toLowerCase(), cgddBean.getEkorg());
            requestMap.put("EKGRP".toLowerCase(), cgddBean.getEkgrp());
            requestMap.put("BUKRS".toLowerCase(), cgddBean.getBukrs());
            requestMap.put("FRGKE".toLowerCase(), cgddBean.getFrgke());
            requestMap.put("ZFLAG".toLowerCase(), cgddBean.getZflag());
            requestMap.put("ZSPBS".toLowerCase(), cgddBean.getZspbs());

            String creator = cgddBean.getCreator();
            if (!"".equals(creator)) {
                String sql = "select id,lastname from hrmresource where loginid='" + creator + "'";
                rs.execute(sql);
                int bool = 0;
                if (rs.next()) {
                    creatorId = Util.null2String(rs.getString("id"));
                    String lastname = Util.null2String(rs.getString("lastname"));
                    writeLog("lastname:" + lastname);
                    bool++;
                }
                if (bool == 0) {
                    message.setFlag("E");
                    message.setId("-300");
                    message.setMessage("创建人OA系统不存在!");
                    return message;
                }
            } else {
                message.setFlag("E");
                message.setId("-300");
                message.setMessage("创建人人为空!");
                return message;
            }
            writeLog("creator:" + creator);

        }

//        获取请求标题
//        String title = "采购订单流程";
        String title = workflowCreateHandler.bulidWorkflowTitle(WorkFlowId, creatorId);
        String requestid = "-1";
        writeLog("title:" + title);

        try {
            requestid = workflowCreateHandler.WorkflowCreateByRequestMap(creatorId, WorkFlowId, title, IsNextFlow, requestMap);
//            判断是否在主表中插入了数据
            String sureMain = "select id from formtable_main_126 where ebeln=? and bedat=? and bsart=?";
            RecordSet sureMainRs = new RecordSet();
            boolean b = sureMainRs.executeQuery(sureMain, cgddBean.getEbeln(), cgddBean.getBedat(), cgddBean.getBsart());
            if (b && sureMainRs.getString("id") != null) {
//                主表插入成功
                if (Util.getIntValue(requestid) > 0) {
                    List<Map<String, String>> list = new ArrayList<>();
                    Map<String, String> map = new HashMap<>();
                    writeLog("cgddDetail1Beans:" + cgddDetail1Beans);
                    if (cgddDetail1Beans != null && cgddDetail1Beans.size() > 0) {
//                    将数据组装成list
                        try {
                            for (int i = 0; i < cgddDetail1Beans.size(); i++) {
                                CgddDetail1Bean cgddDetail1Bean = new CgddDetail1Bean();
                                writeLog("i:" + i);
                                cgddDetail1Bean = cgddDetail1Beans.get(i);
                                if (cgddDetail1Bean != null) {
                                    map = new HashMap<>();
                                    map.put("EBELN".toLowerCase(), cgddDetail1Bean.getEbeln() == null ? "" : cgddDetail1Bean.getEbeln());
                                    map.put("EBELP".toLowerCase(), cgddDetail1Bean.getEbelp() == null ? "" : cgddDetail1Bean.getEbelp());
                                    map.put("KNTTP".toLowerCase(), cgddDetail1Bean.getKnttp() == null ? "" : cgddDetail1Bean.getKnttp());
                                    map.put("EPSTP".toLowerCase(), cgddDetail1Bean.getEpstp() == null ? "" : cgddDetail1Bean.getEpstp());
                                    map.put("MATNR".toLowerCase(), cgddDetail1Bean.getMatnr() == null ? "" : cgddDetail1Bean.getMatnr());
                                    map.put("TXZ01".toLowerCase(), cgddDetail1Bean.getTxz01() == null ? "" : cgddDetail1Bean.getTxz01());
                                    map.put("MENGE".toLowerCase(), cgddDetail1Bean.getMenge() == null ? "" : cgddDetail1Bean.getMenge());
                                    map.put("MEINS".toLowerCase(), cgddDetail1Bean.getMeins() == null ? "" : cgddDetail1Bean.getMeins());
                                    map.put("EEIND".toLowerCase(), cgddDetail1Bean.getEeind() == null ? "" : cgddDetail1Bean.getEeind());
                                    map.put("NETPR".toLowerCase(), cgddDetail1Bean.getNetpr() == null ? "" : cgddDetail1Bean.getNetpr());
                                    map.put("NETWR".toLowerCase(), cgddDetail1Bean.getNetwr() == null ? "" : cgddDetail1Bean.getNetwr());
                                    map.put("MWSKZ".toLowerCase(), cgddDetail1Bean.getMwskz() == null ? "" : cgddDetail1Bean.getMwskz());
                                    map.put("WAERS".toLowerCase(), cgddDetail1Bean.getWaers() == null ? "" : cgddDetail1Bean.getWaers());
                                    map.put("PEINH".toLowerCase(), cgddDetail1Bean.getPeinh() == null ? "" : cgddDetail1Bean.getPeinh());
                                    map.put("MATKL".toLowerCase(), cgddDetail1Bean.getMatkl() == null ? "" : cgddDetail1Bean.getMatkl());
                                    map.put("WERKS".toLowerCase(), cgddDetail1Bean.getWerks() == null ? "" : cgddDetail1Bean.getWerks());
                                    map.put("LGORT".toLowerCase(), cgddDetail1Bean.getLgort() == null ? "" : cgddDetail1Bean.getLgort());
                                    map.put("INFNR".toLowerCase(), cgddDetail1Bean.getInfnr() == null ? "" : cgddDetail1Bean.getInfnr());
                                    map.put("RETPO".toLowerCase(), cgddDetail1Bean.getRetpo() == null ? "" : cgddDetail1Bean.getRetpo());
                                    map.put("BANFN".toLowerCase(), cgddDetail1Bean.getBanfn() == null ? "" : cgddDetail1Bean.getBanfn());
                                    map.put("BNFPO".toLowerCase(), cgddDetail1Bean.getBnfpo() == null ? "" : cgddDetail1Bean.getBnfpo());
                                    map.put("REPOS".toLowerCase(), cgddDetail1Bean.getRepos() == null ? "" : cgddDetail1Bean.getRepos());
                                    map.put("WEBRE".toLowerCase(), cgddDetail1Bean.getWebre() == null ? "" : cgddDetail1Bean.getWebre());
                                    map.put("LOEKZ".toLowerCase(), cgddDetail1Bean.getLoekz() == null ? "" : cgddDetail1Bean.getLoekz());
                                    writeLog("添加到list中的map是：" + map);
                                    list.add(map);
                                }
                            }
                        } catch (Exception e) {
                            message.setFlag("E");
                            message.setId("-200");
                            message.setMessage("明细表数据存在错误");
                        }
                    }
                    writeLog("成功添加了" + list.size() + "条数据");

                    String detailTableName = "formtable_main_126_dt1";
                    String mainId = "";
                    //根据requestId获取主表的id作为明细表的mainId
                    writeLog("此时的requestId是：" + requestid);
                    String getIdSql = "select id from " + detailTableName + " where requestid = " + requestid;
                    RecordSet getIdRs = new RecordSet();
                    getIdRs.execute(getIdSql);
                    if (getIdRs.next()) {
                        mainId = getIdRs.getString("id");
                    } else {
                        message.setFlag("E");
                        message.setId("-200");
                        message.setMessage("获取主表id出错，其中requestId=" + requestid);
                    }
//                明细表字段
                    String[] dtParams = {"EBELN", "EBELP", "KNTTP", "EPSTP", "MATNR", "TXZ01", "MENGE", "MEINS",
                            "EEIND", "NETPR", "NETWR", "MWSKZ", "WAERS", "PEINH", "MATKL", "WERKS", "LGORT", "INFNR", "RETPO",
                            "BANFN", "BNFPO", "REPOS", "WEBRE", "LOEKZ"};
//                将数据插入明细表
                    boolean insertDt = getInsertDtSqls(list, dtParams, "formtable_main_126_dt1", mainId);
                    if (insertDt) {
                        writeLog("明细表插入成功");
                    } else {
                        message.setFlag("E");
                        message.setId("-200");
                        message.setMessage("明细表插入失败");
                    }
                }
            } else {
//                主表插入未成功
                message.setFlag("E");
                message.setId("-200");
                message.setMessage("主表数据添加失败");
            }

        } catch (Exception e) {
            message.setFlag("E");
            message.setId("-200");
            message.setMessage(workflowCreateHandler.expoundRequest(requestid));
            return message;
        }
        writeLog("此时的Message信息是：" + message);
        return message;
    }

    private boolean getInsertDtSqls(List<Map<String, String>> list, String[] dtParams, String tableName, String mainId) {
        String insertSql = "insert into " + tableName + "(mainid,";
        for (int i = 0; i < dtParams.length; i++) {
            if (i != dtParams.length - 1) {
                insertSql += dtParams[i].toLowerCase() + ",";
            } else {
                insertSql += dtParams[i].toLowerCase() + ")";
            }
        }
        insertSql += "values";
        for (int i = 0; i < list.size(); i++) {
            if (i != list.size() - 1) {
                insertSql += "(" + mainId + ",";
                Map<String, String> map = new HashMap<>();
                map = list.get(i);
                for (int i1 = 0; i1 < dtParams.length; i1++) {
                    if (i1 != dtParams.length - 1) {
                        insertSql += map.get(dtParams[i1].toLowerCase()) == null ? "null" : map.get(dtParams[i1].toLowerCase()) + ",";
                    } else {
                        insertSql += map.get(dtParams[i1].toLowerCase()) == null ? "null" : map.get(dtParams[i1].toLowerCase());
                    }
                }
                insertSql += "),";
            } else {
                insertSql += "(" + mainId + ",";
                Map<String, String> map = new HashMap<>();
                map = list.get(i);
                for (int i1 = 0; i1 < dtParams.length; i1++) {
                    if (i1 != dtParams.length - 1) {
                        insertSql += map.get(dtParams[i1].toLowerCase()) == null ? "null" : map.get(dtParams[i1].toLowerCase()) + ",";
                    } else {
                        insertSql += map.get(dtParams[i1].toLowerCase()) == null ? "null" : map.get(dtParams[i1].toLowerCase());
                    }
                }
                insertSql += ")";
            }
        }
        writeLog("执行插入的sql是：" + insertSql);
        RecordSet insertDtRs = new RecordSet();
        return insertDtRs.execute(insertSql);
    }

}
